<template>
  <div
    ref="historyChart"
    class="charts"
    style="width: 100%; height: 400px"
  ></div>
</template>

<script lang="ts">
import * as echarts from 'echarts';

export default {
  name: 'PerformanceMonitorHistoryChart',
  props: {
    hardwareName: {
      type: String,
      default: 'hardware',
    },
    historyData: {
      type: Array,
      default: () => [],
    },
    selected: {
      type: String,
      default: '15 minutes',
    },
    hardwareType: {
      type: String,
      default: 'hardware',
    },
  },
  data() {
    return {
      timer: null,
      historyChart: '',
    };
  },
  computed: {
    displayData() {
      return this.historyData.filter(({ timeStamp }: { timeStamp: string }) => {
        const lastDateTime = new Date(
          this.historyData[this.historyData.length - 1].timeStamp
        );
        if (this.selected === '15 minutes')
          lastDateTime.setMinutes(lastDateTime.getMinutes() - 15);
        if (this.selected === '1 hour')
          lastDateTime.setHours(lastDateTime.getHours() - 1);
        if (this.selected === '12 hours')
          lastDateTime.setHours(lastDateTime.getHours() - 12);
        if (this.selected === '24 hours')
          lastDateTime.setHours(lastDateTime.getHours() - 24);
        if (this.selected === '48 hours')
          lastDateTime.setHours(lastDateTime.getHours() - 48);
        return new Date(timeStamp) > lastDateTime;
      });
    },
  },
  watch: {
    selected() {
      this.historyChart.setOption(this.options(), {
        notMerge: false,
        lazyUpdate: true,
        silent: false,
      });
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  mounted() {
    const unitTransfer = {
      bps: 'b',
      Kbps: 'K',
      Mbps: 'M',
    };

    this.historyChart = echarts.init(this.$refs.historyChart);
    let _this = this;
    const title = this.hardwareName;
    let yAxis: (
      | {
          name: any;
          type: string;
          splitLine: { lineStyle: { color: string } };
          axisLabel: { formatter: (value: number) => string };
          axisLine: { show: boolean; lineStyle: { color: string } };
          splitArea: { show: boolean };
          max: number;
          nameTextStyle?: undefined;
        }
      | {
          name: string;
          type: string;
          splitLine: { lineStyle: { color: string } };
          nameTextStyle: { align: string; padding: number[] };
          axisLine: { show: boolean; lineStyle: { color: string } };
          splitArea: { show: boolean };
          max: number;
          axisLabel?: undefined;
        }
    )[];
    if (this.hardwareType === 'Memory') {
      yAxis = [
        {
          name: _this.$t('pagePerformanceMonitor.usage'),
          type: 'value',
          splitLine: {
            lineStyle: {
              color: '#abcfe8',
            },
          },
          axisLabel: { formatter: (value: number) => value + '%' },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333',
            },
          },
          splitArea: {
            show: false,
          },
          max: 100,
        },
        {
          name:
            this.$t('pagePerformanceMonitor.totalCapacity') +
            _this.historyData[0].capacity +
            _this.historyData[0].unit,
          type: 'value',
          splitLine: {
            lineStyle: {
              color: '#abcfe8',
            },
          },
          nameTextStyle: {
            align: 'left',
            padding: [0, -60],
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333',
            },
          },
          splitArea: {
            show: false,
          },
          max: 100,
        },
      ];
    } else if (this.hardwareType === 'Disk') {
      yAxis = [
        {
          name: _this.$t('pagePerformanceMonitor.usage'),
          type: 'value',
          splitLine: {
            lineStyle: {
              color: '#abcfe8',
            },
          },
          axisLabel: { formatter: (value: number) => value + '%' },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333',
            },
          },
          splitArea: {
            show: false,
          },
          max: 100,
        },
        {
          name:
            _this.$t('pagePerformanceMonitor.free') +
            ':' +
            _this.historyData[0].free +
            _this.historyData[0].freeUnit +
            '\n' +
            this.$t('pagePerformanceMonitor.totalCapacity') +
            _this.historyData[0].capacity +
            _this.historyData[0].freeUnit,
          type: 'value',
          splitLine: {
            lineStyle: {
              color: '#abcfe8',
            },
          },
          nameTextStyle: {
            align: 'left',
            padding: [0, -60],
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333',
            },
          },
          splitArea: {
            show: false,
          },
          max: 100,
        },
      ];
    } else {
      yAxis = [
        {
          name: _this.$t('pagePerformanceMonitor.usage'),
          type: 'value',
          splitLine: {
            lineStyle: {
              color: '#abcfe8',
            },
          },
          axisLabel: { formatter: (value: number) => value + '%' },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333',
            },
          },
          splitArea: {
            show: false,
          },
          max: 100,
        },
      ];
    }

    if (this.hardwareType !== 'NetInterface') {
      this.options = () => {
        return {
          title: [
            {
              text: title,
              left: 'center',
            },
          ],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              lineStyle: {
                color: '#ddd',
              },
            },
            backgroundColor: 'rgba(233,233,233,1)',
            padding: [5, 10],
            textStyle: {
              color: '#7588E4',
            },
            extraCssText: 'box-shadow: 0 0 5px rgba(0,0,0,0.3)',
            valueFormatter: (value: number) => value.toFixed(2) + '%',
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: _this.displayData.map(
                ({ timeStamp }: { timeStamp: string }) => {
                  const date = timeStamp.split(' ')[0];
                  const dateArr = date.match(
                    /(\d{4})-(\d{1,2})-(\d{1,2})/
                  ) as RegExpMatchArray;
                  const [month, day] = [dateArr[2], dateArr[3]];

                  const time = timeStamp.split(' ')[1];
                  const timeArr = time.match(
                    /(\d{2}):(\d{2}):(\d{2})/
                  ) as RegExpMatchArray;
                  const [hour, minute, second] = [
                    timeArr[1],
                    timeArr[2],
                    timeArr[3],
                  ];
                  return `${month}-${day} ${hour}:${minute}:${second}`;
                }
              ),
              axisLabel: {
                formatter: function (value: any) {
                  if (_this.selected === '15 minutes')
                    return (
                      value.split(' ')[1].split(':')[0] +
                      ':' +
                      value.split(' ')[1].split(':')[1]
                    );
                  else if (_this.selected === '1 hour')
                    return (
                      value.split(' ')[1].split(':')[0] +
                      ':' +
                      value.split(' ')[1].split(':')[1]
                    );
                  else if (_this.selected === '12 hours')
                    return (
                      value.split(' ')[1].split(':')[0] +
                      ':' +
                      value.split(' ')[1].split(':')[1]
                    );
                  else if (_this.selected === '24 hours')
                    return '        ' + value.split(' ')[0] + '        ';
                  else if (_this.selected === '48 hours')
                    return '        ' + value.split(' ')[0] + '        ';
                },
              },
            },
          ],
          yAxis: yAxis,
          series: [
            {
              name: _this.$t('pagePerformanceMonitor.usage'),
              type: 'line',
              data: _this.displayData.map(
                ({ usage }: { usage: number }) => usage
              ),
              lineStyle: {
                color: {
                  type: 'linear',

                  colorStops: [
                    {
                      offset: 1,
                      color: '#2acb04',
                    },
                  ],
                  globalCoord: false,
                },
                shadowColor: 'rgba(72,216,191, 0.3)',
                shadowBlur: 10,
                shadowOffsetY: 20,
              },
              symbol: 'none',
              itemStyle: {
                color: '#2acb04',
              },
              smooth: true,
            },
          ],
        };
      };
    } else {
      this.options = () => {
        return {
          title: {
            text: title,
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              lineStyle: {
                color: '#ddd',
              },
            },
            backgroundColor: 'rgba(233,233,233,1)',
            padding: [5, 10],
            textStyle: {
              color: '#7588E4',
            },
            extraCssText: 'box-shadow: 0 0 5px rgba(0,0,0,0.3)',
            valueFormatter: (value: number) => value.toFixed(2) + 'Mbps',
          },
          legend: {
            bottom: 20,
            orient: 'horizontal',
            data: [
              _this.$t('pagePerformanceMonitor.downSpeed'),
              _this.$t('pagePerformanceMonitor.upSpeed'),
            ],
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: _this.displayData.map(
                ({ timeStamp }: { timeStamp: string }) => {
                  const date = timeStamp.split(' ')[0];
                  const dateArr = date.match(
                    /(\d{4})-(\d{1,2})-(\d{1,2})/
                  ) as RegExpMatchArray;
                  const [month, day] = [dateArr[2], dateArr[3]];

                  const time = timeStamp.split(' ')[1];
                  const timeArr = time.match(
                    /(\d{2}):(\d{2}):(\d{2})/
                  ) as RegExpMatchArray;
                  const [hour, minute, second] = [
                    timeArr[1],
                    timeArr[2],
                    timeArr[3],
                  ];
                  return `${month}-${day} ${hour}:${minute}:${second}`;
                }
              ),
              axisLabel: {
                formatter: function (value: any) {
                  if (_this.selected === '15 minutes')
                    return (
                      value.split(' ')[1].split(':')[0] +
                      ':' +
                      value.split(' ')[1].split(':')[1]
                    );
                  else if (_this.selected === '1 hour')
                    return (
                      value.split(' ')[1].split(':')[0] +
                      ':' +
                      value.split(' ')[1].split(':')[1]
                    );
                  else if (_this.selected === '12 hours')
                    return (
                      value.split(' ')[1].split(':')[0] +
                      ':' +
                      value.split(' ')[1].split(':')[1]
                    );
                  else if (_this.selected === '24 hours')
                    return '        ' + value.split(' ')[0] + '        ';
                  else if (_this.selected === '48 hours')
                    return '        ' + value.split(' ')[0] + '        ';
                },
              },
            },
          ],
          yAxis: [
            {
              name: _this.$t('pagePerformanceMonitor.speed'),
              type: 'value',
              splitLine: {
                lineStyle: {
                  color: '#abcfe8',
                },
              },
              axisLabel: {
                formatter: (value: number) =>
                  value +
                  unitTransfer[
                    _this.historyData[0].unit as 'bps' | 'Mbps' | 'Kbps'
                  ],
              },
              axisLine: {
                show: false,
                lineStyle: {
                  color: '#333',
                },
              },
              splitArea: {
                show: false,
              },
              max: _this.historyData[0].maxSpeed,
            },
            {
              name:
                _this.$t('pagePerformanceMonitor.maxSpeed') +
                ':' +
                _this.historyData[0].maxSpeed +
                _this.historyData[0].unit,
              type: 'value',
              splitLine: {
                lineStyle: {
                  color: '#abcfe8',
                },
              },
              nameTextStyle: {
                align: 'left',
                padding: [0, -100],
              },
              axisLine: {
                show: false,
                lineStyle: {
                  color: '#333',
                },
              },
              splitArea: {
                show: false,
              },
              max: _this.historyData[0].maxSpeed,
            },
          ],
          series: [
            {
              name: _this.$t('pagePerformanceMonitor.downSpeed'),
              type: 'line',
              data: _this.displayData.map(
                ({ downSpeed }: { downSpeed: number }) => downSpeed
              ),
              lineStyle: {
                color: {
                  type: 'linear',

                  colorStops: [
                    {
                      offset: 1,
                      color: '#2acb04',
                    },
                  ],
                  globalCoord: false,
                },
              },
              symbol: 'none',
              itemStyle: {
                color: '#2acb04',
              },
              smooth: true,
            },
            {
              name: _this.$t('pagePerformanceMonitor.upSpeed'),
              type: 'line',
              data: _this.displayData.map(
                ({ upSpeed }: { upSpeed: number }) => upSpeed
              ),
              lineStyle: {
                color: {
                  type: 'linear',
                  colorStops: [
                    {
                      offset: 1,
                      color: '#00b4f6',
                    },
                  ],
                  globalCoord: false,
                },
              },
              symbol: 'none',
              itemStyle: {
                color: '#00b4f6',
              },
              smooth: true,
            },
          ],
        };
      };
    }
    this.historyChart.setOption(this.options(), {
      notMerge: false,
      lazyUpdate: true,
      silent: false,
    });
    this.timer = setInterval(() => {
      this.historyChart.resize();
    }, 500);
  },
  methods: {
    options: () => {},
  },
};
</script>

<style></style>
